'use strict';

const PACKAGE_NAME = "ccc-font-assistant";

const fs = require('fs-extra');
const path = require('path');
const scanPath = require('./scanPath');

let resPath = path.join(Editor.Project.path, '/assets');

function batchChangePrefabs(fontUuid, isAddFont) {
  let resourcesPath = path.join(resPath, './');
  let fileDirs = scanPath.findChildDirNames(resourcesPath, null);
  let dirNames = [];
  fileDirs.forEach((element) => {
    let files = scanPath.findFiles(path.join(element.path, element.name), /\.prefab$|\.fire$/, true);
    if (files && files.length > 0) {
      dirNames.push(element.name);
    }

    files.forEach((file) => {
      let dir = path.join(file.path, file.name);
      let prefab = JSON.parse(fs.readFileSync(dir), { encoding: 'utf-8' });
      changePrefab(dir, prefab, fontUuid, isAddFont);
    })
  });

  for (let i = 0; i < dirNames.length; i++) {
    Editor.assetdb.refresh('db://assets/' + dirNames[i]);
  }

  let str = Editor.T(`${PACKAGE_NAME}.addFont`);
  if (!isAddFont) {
    str = Editor.T(`${PACKAGE_NAME}.removeFont`);
  }

  Editor.success(str + Editor.T(`${PACKAGE_NAME}.finish`));
}

function addFont(fontUuid) {
  batchChangePrefabs(fontUuid, true);
}

function removeFont(fontUuid) {
  batchChangePrefabs(fontUuid, false);
}

function changePrefab(fileName, data, fontUUid, isAdd) {
  for (let i = 0; i < data.length; i++) {

    //如果是系统字 则font设为改为 目标字体
    if (data[i].__type__ == 'cc.Label') {
      if (data[i]._isSystemFontUsed) {//系统字
        if (isAdd) {
          data[i]._isSystemFontUsed = false;
          if (!data[i]._N$file) {
            let object = {
              "__uuid__": fontUUid
            }
            data[i]._N$file = object;
          }
        } else {
          if (data[i]._N$file) {
            data[i]._N$file = null;
          }
        }
      } else {//非系统字

        if (!isAdd) {
          if (data[i]._N$file) {
            let object = data[i]._N$file;

            if (object['__uuid__'] == fontUUid) {
              data[i]._N$file = null;
              data[i]._isSystemFontUsed = true;
            }
          }
        } else if (data[i]._N$file) {//非系统字   有字体  就不处理

        } else {//非系统字 但是没有字体
          if (!data[i]._N$file) {
            let object = {
              "__uuid__": fontUUid
            }
            data[i]._N$file = object;
          }
        }
      }
    }

    if (data[i].__type__ == 'cc.RichText') {
      if (data[i]._isSystemFontUsed) {//系统字
        if (isAdd) {//加字体
          data[i]._isSystemFontUsed = false;
          if (!data[i]._N$font) {
            let object = {
              "__uuid__": fontUUid
            }
            data[i]._N$font = object;
          }
        } else {
          if (data[i]._N$font) {
            data[i]._N$font = null;
          }
        }
      } else {//非系统字  
        if (!isAdd) {//移除字体

          if (data[i]._N$font) {
            let object = data[i]._N$font;

            if (object['__uuid__'] == fontUUid) {
              data[i]._N$font = null;
              data[i]._isSystemFontUsed = true;
            }
          }
        } else if (data[i]._N$font) {//非系统字   有字体  就不处理

        } else {//非系统字 但是没有字体
          if (!data[i]._N$font) {
            let object = {
              "__uuid__": fontUUid
            }
            data[i]._N$font = object;
          }
        }
      }
    }
  }

  fs.writeFileSync(fileName, JSON.stringify(data, null, 2), { encoding: 'utf-8' });
}


module.exports = {
  load() {
    // execute when package loaded
    Editor.log("ccc-font-assistant loaded!");
  },

  unload() {
    // execute when package unloaded
    Editor.log("ccc-font-assistant unloaded!");
  },

  // register your ipc messages here
  messages: {
    'openAddFontPanel'() {
      // open entry panel registered in package.json
      Editor.Panel.open('ccc-font-assistant');
    },

    'ccc-font-assistant:addFont'(event, data) {
      let jsonData = data[0];

      let fontUuid = jsonData.fontUuid;

      addFont(fontUuid);
    },

    'ccc-font-assistant:removeFont'(event, data) {
      let jsonData = data[0];

      let fontUuid = jsonData.fontUuid;

      removeFont(fontUuid);
    }
  },
};